package com.atguigu.java;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.junit.Test;

/*
 * FileInputStream/FileOutputStream:处理非文本文件(.jpg,.avi,.mp3,.dat,.doc)使用字节流。
 * FileReader/FileWriter:处理文本文件(.txt)，使用字符流
 * 
 */
public class FileReaderWriterTest {
	
	//不能使用字符流处理非文本文件
	@Test
	public void testReaderWriter1(){
		FileReader reader = null;
		FileWriter writer = null;
		try {
			//1.
			File src = new File("minghui.jpg");
			File dest = new File("minghui1.jpg");
			//2.
			reader = new FileReader(src);
			writer = new FileWriter(dest);
			
			//3.具体的读入、写出的操作
			char[] cbuf = new char[20];
			int len;//记录读入到cbuf中字符的个数
			while((len = reader.read(cbuf)) != -1){
				writer.write(cbuf, 0, len);
				
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(writer != null){
				//4.
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
			if(reader != null){
				
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		
	}
	
	//实现“dbcp.txt”文件的复制
	@Test
	public void testReaderWriter(){
		FileReader reader = null;
//		FileWriter writer = null;
		try {
			//1.
			File src = new File("dbcp.txt");
			File dest = new File("dbcp1.txt");
			//2.
			reader = new FileReader(src);
//			writer = new FileWriter(dest);
			
			//3.具体的读入、写出的操作
			char[] cbuf = new char[20];
			int len;//记录读入到cbuf中字符的个数
			while((len = reader.read(cbuf)) != -1){
//				writer.write(cbuf, 0, len);
				
				String str = new String(cbuf, 0, len);
				System.out.print(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
//			if(writer != null){
//				//4.
//				try {
//					writer.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				
//			}
			if(reader != null){
				
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		
		
	}
}
